const { body, param, query } = require("express-validator");
const {
    validateObjectId,
    validateTitle,
    validateContent,
} = require("../utils/validate");

// 博客列表验证
const listRules = [
    param("id")
        .notEmpty()
        .withMessage("用户id不能为空")
        .bail()
        .custom(async (value) => {
            if (!validateObjectId(value)) {
                throw new Error("用户id不合法");
            }
        }),
    query("page")
        .optional()
        .custom(async (value) => {
            if (!/\d+/.test(value)) {
                throw new Error("页码不合法");
            }
        }),
    query("size")
        .optional()
        .custom(async (value) => {
            if (!/\d+/.test(value)) {
                throw new Error("每页数量不合法");
            }
        }),
];

// 添加博客验证
const addRules = [
    body("title")
        .notEmpty()
        .withMessage("标题不能为空")
        .bail()
        .custom(async (value) => {
            if (!validateTitle(value)) {
                throw new Error("标题限制在4-20个字符");
            }
        }),
    body("content")
        .notEmpty()
        .withMessage("内容不能为空")
        .bail()
        .custom(async (value) => {
            if (!validateContent(value)) {
                throw new Error("内容限制在4-200个字符");
            }
        }),
];

// 删除博客验证
const deleteRules = [
    param("id")
        .notEmpty()
        .withMessage("博客id不能为空")
        .bail()
        .custom(async (value) => {
            if (!validateObjectId(value)) {
                throw new Error("博客id不合法");
            }
        }),
];

// 获取博客验证
const detailRules = [
    param("id")
        .notEmpty()
        .withMessage("博客id不能为空")
        .bail()
        .custom(async (value) => {
            if (!validateObjectId(value)) {
                throw new Error("博客id不合法");
            }
        }),
];

module.exports = { listRules, addRules, deleteRules, detailRules };
